package com.eling.elcms.travel.service.impl;

import com.eling.elcms.community.model.Building;
import com.eling.elcms.core.exception.AppException;
import com.eling.elcms.core.exception.BusinessException;
import com.eling.elcms.core.model.BaseModel;
import com.eling.elcms.core.util.PropertyUtils;
import com.eling.elcms.privilege.model.User;
import com.eling.elcms.privilege.service.IRoleManager;
import com.eling.elcms.privilege.service.IUserManager;
import com.eling.elcms.system.model.ElcmsUser;
import com.eling.elcms.system.service.IElcmsUserManager;
import com.eling.elcms.travel.model.ApprovalRuleRegister;
import com.eling.elcms.travel.model.RuleRegisterParam;
import com.eling.elcms.travel.service.IApprovalRule;
import com.eling.elcms.travel.service.IApprovalRuleRegisterService;
import com.eling.elcms.travel.service.IRuleRegisterParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class BuildingDirectorApprovalRule implements IApprovalRule {
	
	@Autowired
	private IElcmsUserManager elcmsUserManager;
	@Autowired
	private IUserManager userManager;
	@Autowired
	private IRoleManager roleManager;
	@Autowired
	private IRuleRegisterParamService ruleRegisterParamService;
	@Autowired
	private IApprovalRuleRegisterService approvalRuleRegisterService;
	

	@Override
	public Map<String, String> candidatePara() {
		return null;
	}

	@Override
	public User getApproval(String para, BaseModel model) {
		Building building = PropertyUtils.getProperty(model, getParam(model.getClass().getTypeName()));

		List<ElcmsUser> list = elcmsUserManager.queryUsersByBuilding(building.getPkBuilding(), Long.valueOf(22));
		if(list.isEmpty()){
			throw new BusinessException("找不到"+building.getName()+"的楼长");
		}else{
			return list.get(0);
		}
	}

	private String getParam(String modelName) {
		List<ApprovalRuleRegister> arrlist =approvalRuleRegisterService.query(new ApprovalRuleRegister(BuildingDirectorApprovalRule.class.getName()));
		if(!arrlist.isEmpty()){
			RuleRegisterParam ruleRegisterParam = new RuleRegisterParam();
			ruleRegisterParam.setModelName(modelName);
			ruleRegisterParam.setApprovalRuleRegister(arrlist.get(0));
			List<RuleRegisterParam> rrplist =  ruleRegisterParamService.query(ruleRegisterParam);
			if (!rrplist.isEmpty()) {
				return rrplist.get(0).getParam();
			} else {
				throw new  AppException("缺少会员所在楼的楼长参数数据");
			}
		}else{
			throw new  AppException("数据异常");
		}
		
	}

}
